const path = require('path');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');

module.exports = (env, argv) => {
  const config = {
    entry: './note.js',
    output: {
      filename: 'bundle.js',
      path: path.resolve(__dirname, 'dist'),
      clean: true,
    },
    mode: argv.mode || 'development',
    devtool: argv.mode === 'production' ? 'source-map' : 'eval-source-map',
    target: 'node', // Since our app is a Node.js application
    resolve: {
      fallback: {
        "util": require.resolve("util/"),
        "os": require.resolve("os-browserify/browser"),
        "path": require.resolve("path-browserify"),
        "fs": false,
        "crypto": false
      }
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          use: {
            loader: 'babel-loader',
            options: {
              presets: ['@babel/preset-env']
            }
          }
        }
      ]
    },
    plugins: []
  };

  // Add bundle analyzer plugin when analyze flag is set
  if (env && env.analyze) {
    config.plugins.push(new BundleAnalyzerPlugin({
      analyzerMode: 'server',
      openAnalyzer: true,
    }));
  }

  return config;
};
